<?php
/*
 * inc-preview.php
 * Retral/CSCD494 Winter 2009
 * Eastern Washington University
 *
 * File Description:
 * Shows what questions are found on a given exam
 * 
 * Other:
 * 
 */


/* 
 * Set up $page_name
 * This name will be compared to PAGE_NAME in NAV_URLS table (stored in session) and verify permission for given user.
 */
 
$page_name = "Preview";
$page_name = strtoupper($page_name);
$_SESSION['select'] = 1;
$pm = $_SESSION['pagePermissions'];
//Print_r($_SESSION);
// Is user logged in, and has permissions?
if (isset($_SESSION['loggedIn']) && $_SESSION['loggedIn'] !="" && $_SESSION['pagePermissions'][$page_name] == 1)
{
?>
<link rel="stylesheet" href="css/preview.css" type="text/css" media="screen">

<span class="header-text">PREVIEW EXAM</span><br>

<?php
function userAgentIsIE() //found on forum to check user agent. This will help with needing IE overrides
{
    if ( isset($_SERVER['HTTP_USER_AGENT']) && ( strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
        return true;
    else
        return false;
}

if (isset($_REQUEST['exam']))
{
	/*define("ORA_CON_UN", "cscd494");             // username
	define("ORA_CON_PW", "R3tral435");             // password
	define("ORA_CON_DB", "//146.187.134.17:1542/oracle10g"); // connection string
*/
	$conn = oci_connect(ORA_CON_UN, ORA_CON_PW, ORA_CON_DB);

	$examID = $_REQUEST['exam'];
    
    //here is where I add the code to deal with the newly selected question.
    //if the SESSION variables 'selectQID' and 'selectQVersion' have values
    //set, then we're going to check and see if we've been delivered with 
    //a replacement question. We'll update the data in the database, and 
    //then reset the select cycle for another select cycle. 
    
    //if we're in the select cycle AND we've a selected a question to replace AND we have a new question id and version
    if(($_SESSION['select'] == 1) && ($_SESSION['selectQID'] != 0) && (isSet($_POST['questionID'])) && isSet($_POST['questionVersion']))
    {
        $examUpdate = 'BEGIN
                        DELETE FROM exam_question
                        WHERE exam_ID=:examID AND question_ID=:oldQID AND q_Version=:oldQV;
                        INSERT INTO exam_question
                        VALUES (:examID, :qid, :qv);
                       END;';
                      
        $stmtUpdate = oci_parse($conn, $examUpdate);
        oci_bind_by_name($stmtUpdate, 'qid', $_POST['questionID']);
        oci_bind_by_name($stmtUpdate, 'qv', $_POST['questionVersion']);
        oci_bind_by_name($stmtUpdate, 'examID', $_SESSION['selectExam']);
        oci_bind_by_name($stmtUpdate, 'oldQID', $_SESSION['selectQID']);
        oci_bind_by_name($stmtUpdate, 'oldQV', $_SESSION['selectQV']);

        IF(!oci_execute($stmtUpdate))
        {
            echo "IT didn't WORKED!!!!";
            $e = oci_error($stmtUpdate);
            print_r($e);
        }
       $_SESSION['selectQID'] = 0;
       $_SESSION['selectQV'] = 0;
    }
    else
    {
        //echo("IT DID NOT WORK!!!!");
    }
  //print_r($_SESSION);
  //print_r($_POST);

    $_SESSION['selectExam'] = $examID;
	$examQuery = '
		 SELECT ape_user.first_name, ape_user.last_name,
			  exam.date_scheduled, exam.date_created
		 FROM exam
		 INNER JOIN ape_user ON exam.author_id=ape_user.user_id
		 WHERE exam.exam_id=:examID';
	$stmtExam = oci_parse($conn, $examQuery);
	oci_bind_by_name($stmtExam, ':examID', $examID);
	if(!oci_execute($stmtExam))
		print "<p><b>Invalid entry. Please enter an integer.</b></p>";

	$result = oci_fetch_assoc($stmtExam); 
	if ($result['FIRST_NAME'] == "" && $result['LAST_NAME'] == "")
		$examExists = 0;
	else
		$examExists = 1;
	if ($examExists == 1)
	{
		$date = dateFormat($result['DATE_CREATED']);

		echo "<p class='details'>Exam Date: ".
			 dateFormat($result['DATE_SCHEDULED'])."<br>";
		echo "Created: ".dateFormat($result['DATE_CREATED'])."<br>";
		echo "Author: ".$result['FIRST_NAME'];
		echo " ".$result['LAST_NAME']."</p>\n\n";
?>

	<table border=0 width=100%>
		<tr>
			<td><u>Task</u></td><td><u>Type</u></td>
			<td width=80><u>Ratio</u></td>
		</tr><?php
			$examQuery = '
				 SELECT question_id, q_version FROM exam_question
				 WHERE exam_id=:examID';
			$stmtExam = oci_parse($conn, $examQuery);
			oci_bind_by_name($stmtExam, ':examID', $examID);
			if(!oci_execute($stmtExam)) {
				print "<P>Could not find exam requested</P>";
			}

			$query = '
				 SELECT question_type.type_description, question_content.points, 
					  question_content.question_title, question.date_modified, 
					  ape_user.first_name, ape_user.last_name
				   FROM question_content INNER JOIN question 
				 ON question.question_content_id=question_content.question_content_id
				 INNER JOIN question_type 
				 ON question.question_type_code=question_type.type_code
				 INNER JOIN ape_user ON question_content.author_id=ape_user.user_id
				   WHERE question_id=:QID AND q_version = :vNum';

			$stmt = oci_parse($conn, $query);

			$query = '
			SELECT COUNT(*) AS "TOTAL", grade
			FROM student_question WHERE question_id=:QID AND q_version=:vNum
			GROUP BY grade';

			$stmtGrades = oci_parse($conn, $query);

		while($q = oci_fetch_assoc($stmtExam)) {
			$qid = $q['QUESTION_ID'];

			oci_bind_by_name($stmt, ':vNum', $q['Q_VERSION']);
			oci_bind_by_name($stmt, ':QID', $qid);

			oci_bind_by_name($stmtGrades, ':vNum', $q['Q_VERSION']);
			oci_bind_by_name($stmtGrades, ':QID', $qid);
			if(!oci_execute($stmt)) {
				print "<P>Could not find Question $qid</P>";
			}
			oci_execute($stmtGrades);

			$sum = 0;
			$total = 0;
			
			while($row = oci_fetch_assoc($stmtGrades)) {
				$sum += $row["GRADE"] * $row["TOTAL"];
				$total += $row["TOTAL"];
			}

			$avg = round($sum/$total, 1);

			while($row = oci_fetch_assoc($stmt)) {
				print "<tr>\n";
				print "\t\t<td>";
				print "<a class='expand' name='".$row['QUESTION_TEXT']."' ";
				//print "id=$qid href='index.php?page=question&id=$qid&ver=";
				print "id=$qid href='index.php?page=question&examId=$examID&id=$qid&ver=";
				if (!userAgentIsIE()) //Use javascript if not IE
					print $q["Q_VERSION"]."'>".$row['QUESTION_TITLE']."</td>\n";
				else //Using IE: , just use new target on minimized frame display (Javascript workaround)
					print $q["Q_VERSION"]."' target='_viewEdit'>".$row['QUESTION_TITLE']."</td>\n";
				print "\t\t<td>".$row['TYPE_DESCRIPTION']."</td>\n";
				print "\t\t<td>$avg/".$row['POINTS']."</td>\n";

                //if we are still selecting
                if($_SESSION['select'] == 1)
                    {
                    echo "<form action ='?page=qSelect' method = 'POST'>";
                    echo("<td><input type='submit' class='button' value='Select'/></td>");
                    echo("<input type='hidden' value='".$qid."'name='questionID'> ");
                    echo("<input type='hidden' value='".$q['Q_VERSION']."'name='questionVersion'> ");
					echo("<input type='hidden' value='".$row['type_description']."'name='type'> ");
                    echo"</form>";
                    }
				print "\t</tr><tr class='hidden' id='q$qid'>\n";
				print "\t\t<td colspan=2>\n";
				print "\t\t\t<p>Modified: ".
					 dateFormat($row['DATE_MODIFIED'])."<br>\n";
				print "\t\t\tAuthor: ".$row['FIRST_NAME']." ";
				print $row['LAST_NAME']."<br>\n";
				print "\t\t\t<a class='comment' ";
				print "id='".$qid."c' href='#'>comments</a></p>\n";
				print "\t\t\t<div class='hidden' id='q".$qid."c'>";
				print buildCommentTable($conn, $qid)."</div>\n";
				print "\t\t<td valign='top'><a class='view' name='".$row['QUESTION_TEXT']."' ";
				print "\t\t   href='index.php?page=question&id=$qid&ver=";
				if (!userAgentIsIE()) //If using non-IE browser
					print $q["Q_VERSION"]."&min=5'>view</a></td>"; //set min=0,1, or 2 to add/remove page elements
				else //make a popup
					print $q["Q_VERSION"]."&min=5' target=\"_viewEdit\">view</a></td>"; //set min=0,1, or 2 to add/remove page elements
				print "\t</tr>";
			}
		}
	} //end if first/last name == null (exam does not exist)
	oci_free_statement($stmt);
	oci_free_statement($stmtExam);

	if ($examExists == 1) 
	{
			print "</table>\n";

			$query = '
				SELECT count(DISTINCT student_id) AS "STUDENTS" FROM student_question
				WHERE exam_id=:examID';

			$stmt = oci_parse($conn, $query);
			oci_bind_by_name($stmt, ':examID', $examID);

			if(!oci_execute($stmt))
				print "<P>Faild to count students</P>";

			$result = oci_fetch_assoc($stmt);

			if($result["STUDENTS"] > 0) {
				echo "<h3>Students ".$result["STUDENTS"]."</h3>\n\n";

				$query = '
					SELECT DISTINCT student_id FROM student_question
				WHERE exam_id=:examID';

				$stmt = oci_parse($conn, $query);
				oci_bind_by_name($stmt, ':examID', $examID);

				if(!oci_execute($stmt))
					print "<P>Faild to get students</P>";

				while($row = oci_fetch_assoc($stmt)) {
					echo "Student ID: <a href='?page=student&id=".$row["STUDENT_ID"];
					echo "'>".$row["STUDENT_ID"]."</a><br>\n";
				}
			}
	} //end if examExists ==1
	
	//Close DB connection
	oci_close($conn);

	
	
	//Package Button
	
	if(array_key_exists("exam", $_REQUEST) && $examExists == 1) {
		?>
		<form action="http://http://cscd494-l.cslabs.ewu.edu:8080/apegen" method="POST">
		<input type="hidden" name="examID" id="examID" value="<?php echo $examID; ?>" />
		<input type="hidden" name="runCode" id="runCode" value="package" />
	
		<input type="submit" class="button" value="Package" />
		</form>
		<?php
	//	print "<input type='submit' class='button' value='Package' />\n";
	} else {
?>
<tr>
<td>
</td>
</tr>
</table>
<?php
 } 
 ?>

<script type="text/javascript"
	src="script/preview.js" language="javascript"></script>

<?php
} //end if isset exam

/*else*/  // don't use else - show this if invalid exam ID or not set exam!
if (!isset($_REQUEST['exam']) || $examExists == 0)
{
?>
<tr>
<td>

<?php
if (!isset($_REQUEST['exam']))
	echo "<b>Choose An Exam:</b><br>";
else //exam was specified...check is it valid?
{
	if ($examExists == 0)
		echo "<span style=\"color:red;font-weight:bold;\">Invalid Exam ID</span><br>";
}
?>
<br>
<script language="javascript">
function blurCheck()
{
	if (document.getElementById("exam").value == '')
	{
		document.getElementById("exam").style.color = '#ADADAD'
		document.getElementById("exam").value = 'Enter ID';
		document.getElementById("viewButton").disabled = true;
		
	}
}

function onlyNumeric(e) 
{
	var keyCode=e.charCode ? e.charCode : e.keyCode;
	
	//If isn't backspace, left arrow, right arrow, enter (for submitting) or numeric, return false
	if (keyCode!=8 && keyCode !=13 && (keyCode < 48 || keyCode > 57)) 
		return false;
	else
		return true;
} 

function clicked(id)
{
	if (id.value == 'Enter ID')
	{
		id.value='';
		document.getElementById("viewButton").disabled=false;
		id.style.color='#121212';
	}
}

</script>
<form action="index.php" name="viewForm" id="viewForm" method="GET">
<input type="hidden" name="page" id="page" value="preview">
Exam ID: <input type="text" name="exam" id="exam" value="Enter ID" onkeypress="return onlyNumeric(event);" onclick="clicked(this);" onblur="blurCheck();" style="color:#ADADAD;font-size:10px;"><br/><br/>
<input type="submit" id="viewButton" class="button" value="View Exam" disabled>
</form>


</td>
</tr>
<?php
} //end else no exam id
} //end if logged in
else
{
	echo "Invalid credentials";
	echo "<META http-equiv=\"refresh\" content=\"0;URL=index.php?page=login&ld=0\">";
}	


/*
 * Builds a table that contains the comments.
 * TODO: In the future there should be a link that
 * lets the author of a comment edit their comment.
 */
function buildCommentTable($conn, $qid) {
	$response = '
		<table border=0 cellpadding=5>';

	$query = '
		SELECT ape_user.user_id, comment_date, comments,
		     ape_user.first_name, ape_user.last_name 
		FROM question_comment 
		INNER JOIN ape_user 
		ON ape_user.user_id = question_comment.user_id
		WHERE question_id=:QID';

	$stmt = oci_parse($conn, $query);
	oci_bind_by_name($stmt, ':QID', $qid);

	if(!oci_execute($stmt))
		print "<P>Failed to query for comments.</P>";

	while($row = oci_fetch_assoc($stmt)) {
		$response .= "
				<tr><td>
					<p>".$row['COMMENTS']." -<i>".$row['FIRST_NAME']." ".$row["LAST_NAME"]."
					(".dateFormat($row['COMMENT_DATE']).") </i></p>
				</td></tr>";
	}

	$response .= '</table>';

	return $response;
}
?>
